<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { Search, Refresh, Finished } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

import { getTbListDataApi2, updateCaptureIDS } from "@/api/capture-tb/index"

import { type FormInstance, ElMessage, type FormRules } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import useClipboard from "vue-clipboard3"
import { checkPhoneNumber, checkID, checkName } from "@/utils/validate"
import { shortcuts } from "@/utils/dateSet"
import { formatDateTime } from "@/utils"

defineOptions({
  name: "CaptureListTb2"
})

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const userStore = useUserStore()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)

// #region 查
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]
const searchFormRef = ref<FormInstance | null>(null)

// 搜索内容
const searchData = reactive<any>({
  time: "",
  tradeId: "",
  sellerFlag: ""
})

const formRules: FormRules = reactive({
  idCardName: [{ required: true, validator: checkName, trigger: "blur" }],
  name: [{ required: true, validator: checkName, trigger: "blur" }],
  consignee: [{ required: true, validator: checkName, trigger: "blur" }],
  // handleMobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }],
  idCard: [{ required: true, validator: checkID, trigger: "blur" }],
  mobile: [{ required: true, validator: checkPhoneNumber, trigger: "blur" }]
  // address: [{ required: true, trigger: "blur", message: "请输入地址" }]
})

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
  }
  paginationData.currentPage = 1
}
// #endregion

const tableData = ref<any>([])
const getTableData = async () => {
  loading.value = true
  await getTbListDataApi2({
    startTime: new Date(searchData.time[0]).getTime() || null,
    endTime: new Date(searchData.time[1]).getTime() || null,
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    id: searchData.tradeId,
    sellerFlag: searchData.sellerFlag
  })
    .then((res: any) => {
      paginationData.total = res.data.total

      if (res.data.orderList) {
        tableData.value = res.data.orderList
      } else {
        tableData.value = []
      }
      loading.value = false

      tableData.value.forEach((element: any) => {
        // console.log(element, 22)
        comboList.value.forEach((item: any) => {
          if (element.platformSkuId == item.code) {
            // 如果有匹配套餐,那么赋值,可以勾选提交
            element.TJstate = 3
          }
        })
      })
    })
    .finally(() => {
      loading.value = false
    })
}

// #region 套餐
import { getComboDataApi } from "@/api/combo-jd"
const comboList = ref<any>([])
getComboDataApi({
  page: 1,
  size: 10000,
  type: "tb",
  userId: userStore.usernameID
}).then((res: any) => {
  comboList.value = res.data.list
})
// #endregion

// #region 查看详情
const formData = reactive<any>({ data: {} })
const seeState = ref<string>("")
const dialogVisible = ref<boolean>(false)

//查看详情
const handleSeeInfo = async (row: any) => {
  seeState.value = "see"
  rowData(row, false)
}
// row通用
const rowData = async (row: any, PL: boolean) => {
  formData.data = JSON.parse(JSON.stringify(row))
  if (!PL) {
    dialogVisible.value = true
    dataArr.value.push(formData.data)
  } else {
    dataArr.value.push(row)
  }
}

// #endregion

// #region 批量提交
const dataArr = ref<any>([])
const tableRef = ref<any>(null)

// 订单上传接口
const good_sku = ref<any>("")
const pushDy = async (data: any) => {
  const datainfo = data[0]
  console.log(datainfo.platformSkuId)
  comboList.value.filter((item: any) => {
    if (item.code === datainfo.platformSkuId) {
      good_sku.value = item.systemId ? item.systemId : item.heId
    }
  })
  console.log(good_sku.value)
  if (!good_sku.value) {
    ElMessage.warning("商品未与系统套餐做匹配，请先配置套餐!")
    return
  }
  await updateCaptureIDS(dataArr.value).then((res: any) => {
    // console.log(res, 1923)
    if (res.code == 200) {
      dataArr.value = []
      tableRef.value?.clearSelection()
      ElMessage.success(res.message)
      getTableData()
      dialogVisible.value = false
    } else {
      ElMessage.error(res.message)
    }
  })
}
//单次提交
const handleAdd = async (row: any) => {
  rowData(row, false)
}
const handlePushOne = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      pushDy(dataArr.value)
    } else {
      return false
    }
  })
}

// #endregion

//  #region 清除规则报错信息
const currentUpdateId = ref<undefined | string>(undefined)
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  currentUpdateId.value = undefined
  seeState.value = ""
  dataArr.value = []
  formData.data = {}
  clearValidate()
}
// #endregion

//复制套餐编码

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}
// #region 批量提交 批量选择
// 根据不同状态禁用批量提交

const selectable = (row: any) => {
  if (row.sellerFlag == 3) {
    return false
  } else if (row.TJstate !== 3) {
    return false
  } else {
    return true
  }
}
const handleSelectionChange = (val: any) => {
  dataArr.value = []
  // console.log(val, 1023)
  dataArr.value = val
  console.log(dataArr.value, 111)
}
//批量提交
const addItems = async () => {
  updateCaptureIDS(dataArr.value).then(() => {
    ElMessage.success("批量提交成功")
    getTableData()
  })
}
// #endregion

/**加密 */
const toHideString = (val: any, len: any) => {
  if (val.length == 2) {
    return `${val.substring(0, len)}*****${val.substring(val.length)}`
  } else {
    return `${val.substring(0, len)}*****${val.substring(val.length - len)}`
  }
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper" v-loading="loading">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="tradeId" label="订单ID">
          <el-input v-model.trim="searchData.tradeId" clearable placeholder="请输入" style="width: 240px" />
        </el-form-item>
        <el-form-item prop="time" label="订单日期">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            :default-time="defaultTime1"
          />
        </el-form-item>
        <el-form-item prop="sellerFlag" label="卖家备注(颜色)">
          <el-select v-model="searchData.sellerFlag" clearable placeholder="请选择" style="width: 200px">
            <el-option label="灰色" value="0" />
            <el-option label="红色" value="1" />
            <el-option label="黄色" value="2" />
            <el-option label="绿色" value="3" />
            <el-option label="蓝色" value="4" />
            <el-option label="紫色" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button type="primary" :icon="Finished" @click="addItems">批量提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" v-loading="loading">
      <div class="table-wrapper">
        <el-table :data="tableData" @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" :selectable="selectable" width="50" align="center" />
          <el-table-column prop="tradeId" label="订单ID" align="center" />
          <el-table-column label="商品信息" align="center" width="300">
            <template #default="scope">
              <el-row>
                <el-col :span="8" style="text-align: center; vertical-align: middle">
                  <!-- <p><img :src="scope.row.orders.order[0].pic_path" alt="" width="60" height="60" /></p> -->
                </el-col>
                <el-col :span="16">
                  <p :title="scope.row.platformProductName">
                    {{ scope.row.platformProductName }}
                  </p>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="套餐匹配" align="center" width="360">
            <template #default="scope">
              <el-select v-model="scope.row.platformSkuId" clearable filterable placeholder="请选套餐">
                <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
              </el-select>
              <el-link type="primary" style="margin-left: 10px" @click="copy(scope.row.platformSkuId)"
                ><el-icon><DocumentCopy /></el-icon>复制编码</el-link
              >
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="订单创建时间" width="180" align="center">
            <template #default="scope">
              <text> {{ formatDateTime(scope.row.createTime) }}</text>
            </template>
          </el-table-column>
          <el-table-column label="收件信息" align="center">
            <template #default="scope">
              <p>{{ toHideString(scope.row.receiverName, 1) }}</p>
              <p>{{ toHideString(scope.row.receiverMobile, 4) }}</p>
              <p>
                {{ scope.row.receiverState }} {{ scope.row.receiverCity }} {{ scope.row.receiverDistrict }}
                {{ toHideString(scope.row.receiverAddress, 0) }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="seller_flag" label="卖家备注(颜色)" align="center">
            <template #default="scope">
              <p>
                <span
                  class="flag"
                  :class="{
                    grey: scope.row.sellerFlag == 0,
                    red: scope.row.sellerFlag == 1,
                    yellow: scope.row.sellerFlag == 2,
                    green: scope.row.sellerFlag == 3,
                    blue: scope.row.sellerFlag == 4,
                    purple: scope.row.sellerFlag == 5
                  }"
                />
              </p>
              <!-- <p :title="scope.row.remark" class="esp">{{ scope.row.remark }}</p> -->
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleAdd(scope.row)" style="margin: 10px 0"
                >修改提交</el-button
              ><br />
              <el-button type="primary" text bg size="small" @click="handleSeeInfo(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="[10, 20]"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog v-model="dialogVisible" :title="seeState === 'see' ? '查看详情' : '提交'" @close="resetForm" width="60%">
      <el-form ref="formRef" :rules="formRules" :model="formData.data" label-width="100px" label-position="left">
        <el-form-item prop="tradeId" label="订单ID">
          <el-input v-model="formData.data.tradeId" placeholder="请输入订单编号" disabled />
        </el-form-item>
        <el-form-item prop="createTime" label="创建时间">
          <div class="el-input is-disabled">
            <div class="el-input__wrapper">
              <span class="el-input__inner">{{ formatDateTime(formData.data.createTime) }}</span>
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="receiverName" label="用户姓名">
          <el-input v-model="formData.data.receiverName" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="idCard" label="身份证号">
          <el-input v-model="formData.data.idCard" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input v-model="formData.data.remark" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="productName" label="套餐名">
          <el-select
            v-model="formData.data.platformSkuId"
            clearable
            filterable
            placeholder="请选套餐"
            style="width: 100%"
          >
            <el-option v-for="item in comboList" :key="item.id" :label="item.systemName" :value="item.code" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="productPic" label="套餐主图">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="formData.data.orders.order[0].pic_path"
              :zoom-rate="1.2"
              :initial-index="4"
              fit="cover"
            />
          </div>
        </el-form-item> -->
        <el-form-item prop="buyerMessage" label="买家留言">
          <el-input v-model="formData.data.buyerMessage" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="sellerMemo" label="卖家备注">
          <el-input v-model="formData.data.sellerMemo" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item prop="receiverName" label="收货人姓名">
          <el-input v-model="formData.data.receiverName" placeholder="请输入" :disabled="seeState === 'see'" />
        </el-form-item>
        <el-form-item prop="receiverMobile" label="联系电话">
          <el-input
            v-model="formData.data.receiverMobile"
            maxlength="11"
            show-word-limit
            placeholder="请输入"
            :disabled="seeState === 'see'"
          />
        </el-form-item>
        <div>
          <el-form-item prop="receiverState" label="收货省份">
            <el-input v-model="formData.data.receiverState" placeholder="请输入" :disabled="seeState === 'see'" />
          </el-form-item>
          <el-form-item prop="receiverCity" label="收货市">
            <el-input v-model="formData.data.receiverCity" placeholder="请输入" :disabled="seeState === 'see'" />
          </el-form-item>
          <el-form-item prop="receiverDistrict" label="收货区">
            <el-input v-model="formData.data.receiverDistrict" placeholder="请输入" :disabled="seeState === 'see'" />
          </el-form-item>
          <el-form-item prop="receiverAddress" label="详细地址">
            <el-input v-model="formData.data.receiverAddress" placeholder="请输入" :disabled="seeState === 'see'" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePushOne" v-if="seeState !== 'see'">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  .btn {
    width: 100%;
    height: 100%;
    display: flex;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
:deep(.el-upload-list__item .el-icon--close-tip) {
  top: 20px;
  left: 10px;
  right: 0;
}
.doing {
  color: #b88230;
}
.error {
  color: red;
}
.success {
  color: #67c23a;
}
.again {
  color: #c45656;
}
:deep(.el-popper) {
  max-width: 50% !important;
}
.date-box {
  width: 340px !important;
}
.text-ellipsis {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
</style>
<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
.pbox {
  line-height: 2em;
}
.flag {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
}
.red {
  background: red;
}
.yellow {
  background: rgb(255, 220, 0);
}
.green {
  background: green;
}
.blue {
  background: blue;
}
.purple {
  background: purple;
}
.grey {
  background: gray;
}
.goodInfo {
  text-align: left;
}
.esp {
  /* width: 180px; */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  cursor: pointer;
}
</style>
